package com.wcq.dessert.core;

import java.util.LinkedList;

/**
 * FiberPool属于一个线程，此线程的多个协程操作该数据不会有线程安全问题
 */
public class FiberPool {
    private final static int MAX_SIZE = 50;
    private LinkedList<PortFiber> pool = new LinkedList<>();
    Port port;

    public int counter;

    public FiberPool(Port port){
        this.port = port;
        for (int i = 0; i < MAX_SIZE; i++) {
            pool.add(new PortFiber(++counter, this));
        }
    }

    public PortFiber newFiber(){
        return new PortFiber(++counter, this);
    }

    /**
     * 申请协程
     * @return
     */
    public PortFiber apply(){
        if (pool.isEmpty()){
            return new PortFiber(++counter, this);
        }
        return pool.removeFirst();
    }

    /**
     * 回收
     * @param portFiber
     */
    public void recycle(PortFiber portFiber) {
        if (pool.size() >= MAX_SIZE){
            portFiber.destroy();
            return;
        }
        pool.add(portFiber);
    }

    public int size() {
        return pool.size();
    }
}
